const TAB_NAME='big_user_id';

/**
 * 用户数据模型
 */
module.exports = class UserId extends require('./model_pool')
{
  // 记录一个uid及用户权限信息，有则覆盖，fields为数据对象
  static recordUser(uid, fields)
  {
    return new Promise((resolve,reject)=>{
      let kvArray = [];
      for (let key in fields) {
        let value = fields[key];
        kvArray.push(`${key}='${value}'`);
      }
      let sql = 'UPDATE '+TAB_NAME+' SET '+kvArray.join(',')+' WHERE id=?';
      this.query(sql, [uid]).then((res)=>{
        if (res.affectedRows == 0) {
          this.insertUser(uid, fields).then((res)=>{
            resolve(res);
          })
        } else {
          resolve(res.insertId);
        }
      }).catch(err=>{
        console.log('['+uid+']['+TAB_NAME+'] recordUser faild: '+err.message);
        reject(err);
      })
    })
  }

  // 插入新用户记录
  static insertUser(uid, fields)
  {
    return new Promise((resolve,reject)=>{
      let keyArr = ['id'];
      let valArr = [uid];
      for(let key in fields){
        keyArr.push(`${key}`);
        valArr.push(`'${fields[key]}'`);
      }
      let sql = 'INSERT INTO '+TAB_NAME+' ('+keyArr.join(',')+')'+' VALUES('+valArr.join(',')+')';
      this.query(sql, []).then((res)=>{
        resolve(res.insertId);
      }).catch(err=>{
        console.log('['+uid+']['+TAB_NAME+'] insertUser faild:'+err.message);
        reject(err);
      })
    })
  }

  //获取用户权限, fields为逗号分隔的字符串
  static getFields(uid, fields)
  {
    return new Promise((resolve,reject)=>{
      let sql='SELECT '+fields+' FROM '+TAB_NAME+' WHERE id=?';
      this.query(sql, [uid]).then(res=>{
        if (res.length) resolve(res[0]);
        else resolve(null);
      }).catch(err=>{
          console.log('getFields query faild: ' + err.message)
          reject(err);
      })
    })
  }
}